package se.webbzon.oschi01.tools;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;

import se.webbzon.oschi01.singleton.Singleton;

public class ToolLoader implements Singleton {
	
	private static final String filename = "tools.properties";
	
	public Collection<Tool> loadTools() throws IOException {
		URL url = getClass().getResource(filename);
		Collection<Tool> tools = new ArrayList<Tool>();
		if (url == null) {
			throw new IOException("The resource \"" + filename + "\" could not be found.");
		} else try (InputStream is = url.openStream()) {
			BufferedReader reader = new BufferedReader(new InputStreamReader(is));
			String line = reader.readLine();
			while (line != null) {
				if (!line.startsWith("#") && !line.isEmpty()) try {
					Class<?> clazz = getClass().getClassLoader().loadClass(line);
					if (Tool.class.isAssignableFrom(clazz)) try {
						tools.add((Tool) clazz.newInstance());
					} catch (Throwable e) {
						throw new IOException(e);
					}
				} catch (ClassNotFoundException e) {
					throw new IOException(e);
				}
				line = reader.readLine();
			}
		} catch (IOException e) {
			throw e;
		}
		return tools;
	}

}
